package com.heima.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.heima.crm.common.result.Result;
import com.heima.crm.mapper.SysMenuMapper;
import com.heima.crm.pojos.dtos.MenuPageDTO;
import com.heima.crm.pojos.entity.SysMenu;
import com.heima.crm.service.SysMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

/*    @Override
    public Result findList(MenuPageDTO dto) {
        //展示所有
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        if (dto.getMenuName()!=null && !"".equals(dto.getMenuName())){
            wrapper.like(SysMenu::getMenuName,dto.getMenuName());
        }
        if (dto.getStatus()!=null && !"".equals(dto.getStatus())){
            wrapper.eq(SysMenu::getStatus,dto.getStatus());
        }

        wrapper.select(SysMenu.class, info -> !info.getColumn().equals("child_menus"));
        List<SysMenu> records = sysMenuMapper.selectList(wrapper);

        //封装返回数据
        List<SysMenu> list = setChildMenus(records);

        return Result.success(list);

    }*/

    private List<SysMenu> setChildMenus(List<SysMenu> records) {
        Map<Long, List<SysMenu>> map = new HashMap<>();
        for (SysMenu item : records) {
            Long parentId = item.getParentId();
            if (!map.containsKey(parentId)) {
                map.put(parentId, new ArrayList<>());
            }
            map.get(parentId).add(item);
        }

        List<SysMenu> topLevelList = new ArrayList<>(); // 最终封装的目标列表
        Long rootParentId = 0L; // 根节点的parentId，假设为0
        populateChildren(rootParentId, topLevelList, map);
        return topLevelList;
    }

    void populateChildren(Long parentId, List<SysMenu> targetList, Map<Long, List<SysMenu>> map) {
        List<SysMenu> children = map.get(parentId);
        if (children != null) {
            for (SysMenu child : children) {
                targetList.add(child);
                populateChildren(child.getMenuId(), targetList, map);
            }
        }
    }

    @Override
    public Result findList(MenuPageDTO dto) {
        //展示所有
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        if (dto.getMenuName()!=null && !"".equals(dto.getMenuName())){
            wrapper.like(SysMenu::getMenuName,dto.getMenuName())
                    .or().like(SysMenu::getParentMenu,dto.getMenuName());
        }
        if (dto.getStatus()!=null && !"".equals(dto.getStatus())){
            wrapper.eq(SysMenu::getStatus,dto.getStatus());
        }

        wrapper.select(SysMenu.class, info -> !info.getColumn().equals("child_menus"));
        List<SysMenu> records = sysMenuMapper.selectList(wrapper);

        //冒泡排序
        bubbleSort(records);

        SysMenu menu1 = records.get(0);
        List<SysMenu> list = records.stream().filter(menuVO ->
                menuVO.getParentId()==menu1.getParentId()
        ).map((menu)->{
            menu.setChildMenus(getChildrenData(menu,records));
            return menu;
        }).collect(Collectors.toList());
        List<SysMenu> menuList = list.stream().filter(menu -> menu.getStatus() == dto.getStatus())
                .filter(menu -> menu.getMenuName().contains(dto.getMenuName()))
                .collect(Collectors.toList());

        return Result.success(list);
    }

    private void bubbleSort(List<SysMenu> list) {
        int n = list.size();
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (list.get(j).getParentId() > list.get(j + 1).getParentId()) {
                    // 交换相邻元素的位置
                    SysMenu temp = list.get(j);
                    list.set(j, list.get(j + 1));
                    list.set(j + 1, temp);
                }
            }
        }
    }

    //获取孩子（下级目录）的方法，递归实现
    private List<SysMenu> getChildrenData(SysMenu root, List<SysMenu> all) {
        List<SysMenu> children = all.stream().filter(menuVO ->
                menuVO.getParentId().equals(root.getMenuId())
        ).map(menuVO -> {
            menuVO.setChildMenus(getChildrenData(menuVO,all));
            return menuVO;
        }).collect(Collectors.toList());
        return children;
    }

    @Override
    public Result add(SysMenu menu) {
        SysMenu exist = sysMenuMapper.selectOne(new LambdaQueryWrapper<SysMenu>()
                .eq(SysMenu::getMenuName, menu.getMenuName()));
        if (exist!=null){
            return Result.error("菜单名已存在");
        }
        sysMenuMapper.insert(menu);
        return Result.success();
    }

    @Override
    public Result findById(Long menuId) {
        SysMenu sysMenu = sysMenuMapper.selectById(menuId);
        return Result.success(sysMenu);
    }

    @Override
    public Result update(SysMenu menu) {
        sysMenuMapper.updateById(menu);
        return Result.success();
    }

    @Override
    public Result deleteById(Long menuId) {
        List<SysMenu> list = sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>()
                .eq(SysMenu::getParentId, menuId));
        if (list!=null){
            return Result.error("有子菜单不能删除");
        }
        sysMenuMapper.deleteById(menuId);
        return Result.success();
    }

    @Override
    public Result parentName() {
        List<SysMenu> sysMenus = sysMenuMapper.selectList(null);
        for (SysMenu sysMenu : sysMenus) {
            LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<SysMenu>()
                    .eq(SysMenu::getMenuId, sysMenu.getParentId());
            SysMenu menu = sysMenuMapper.selectOne(wrapper);
            if (menu!=null){
                sysMenu.setParentMenu(menu.getMenuName());
                sysMenuMapper.updateById(sysMenu);
            }
        }
        return Result.success();
    }
}
